<!-- 岗位需求申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="applicationId" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.applicationId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.applicationId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请部门" prop="applicationDeptId" required>
          <h-select-depart-input
            v-model="model.applicationDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
						disabled
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请团队" prop="teamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择申请团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
          />
        </u-form-item>
        <u-form-item label="编制人数" prop="staffingQuantity" required>
					<h-number-input placeholder="请输入编制人数" v-model="model.staffingQuantity" :digit="0" :min="0" :max="99999999"></h-number-input>
        </u-form-item>
        <u-form-item label="实际人数" prop="practicalQuantity" required>
					<h-number-input placeholder="请输入实际人数" v-model="model.practicalQuantity" :digit="0" :min="0" :max="99999999"></h-number-input>
        </u-form-item>
        <u-form-item label="所需人数" prop="requireQuantity" required>
					<h-number-input placeholder="请输入所需人数" disabled v-model="model.requireQuantity" :digit="0" :min="0" :max="99999999"></h-number-input>
        </u-form-item>
        <u-form-item label="增岗事由" prop="requireReason">
          <h-select-input-tag
            class="w-100"
            v-model="model.requireReason"
            objectField="model.requireReason"
            placeholder="请选择增岗事由"
            border="surround"
            dictName="require_reason"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea confirm-type="send" v-model="model.remark" placeholder="请输入备注" maxlength="500"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">岗位明细</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addForm">新增</u-button>
        </view>
				<view v-for="(item, index) in formData" :key="index">
					<FormInfo :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" />
				</view>
				<!-- @close="closeFormModal" @open="openFormModal" -->
        <u-popup :round="10" mode="bottom" :show="showFormModal" >
          <JobForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="closeFormModal" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" text="保存草稿" :plain="true" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
			<view style="height: 100rpx;"></view>
    </u-form>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info,edit } from '@/api/hr/ErpHrPostRequirementBillForm'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import fileList from '@/pages/synergy/components/fileList.vue'
import JobForm from './components/JobForm.vue'
import FormInfo from './components/JobFormInfo.vue'
export default {
  name: 'ErpHrPostRequirementBillForm',
  components: {
    fileList,
    JobForm,
    FormInfo,
		ProcessNodeConfiguration
  },
  data() {
    return {
      index: null,
      showFormModal: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      basicForm: {},
      formData: [],
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        applicationId: '',
        applicationDeptId: '',
        createTime: '',
        teamId: '',
        staffingQuantity: '',
				practicalQuantity: '',
				requireQuantity: '',
        remark: '',
        // 附件
        attachments: null,
      },
      rules: {
				billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				applicationDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				applicationId: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        teamId: [{ required: true, message: '请选择团队!', trigger: 'change' }],
        staffingQuantity: [{ required: true, message: '请输入编制人数!', trigger: ['blur', 'change'] }],
        practicalQuantity: [{ required: true, message: '请输入实际人数!', trigger: ['blur', 'change'] }],
        requireQuantity: [{ required: true, message: '请输入所需人数!', trigger: ['blur', 'change'] }],
      },
			isSubmit: false,
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_hr_post_requirement_bill',
			formUrl: "erp/hr/post/modules/ErpHrPostRequirementBillForm",
			formUrlMobile: "/pages/synergy/erpHrPostRequirementBillList",
			processId:"1540228876863561729",
			beanName:"erpHrPostRequirementBillServiceImpl"
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (this.id) {
		  this.initInfo()
		} else {
		  this.initForm()
		  this.initBillNo()
		}
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
			this.$nextTick(() => {
				this.openFormModal()
			})
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
			if(this.formData.length){
				let requireQuantity=0;
				this.formData.forEach(item=>{
					if(item.requireQuantity){
						requireQuantity+=Number(item.requireQuantity);
					}
				})
				this.$set(this.model,"requireQuantity",requireQuantity)
			} else {
				this.$set(this.model,"requireQuantity",0)
			}
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
			this.showFormModal = false
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = Object.assign({},this.basicForm)
      this.$refs.dataForm.edit()
    },
    addForm() {
      this.index = null
			this.basicForm = {}
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
      if(this.formData.length){
				let requireQuantity=0;
				this.formData.forEach(item=>{
					if(item.requireQuantity){
						requireQuantity+=Number(item.requireQuantity);
					}
				})
				this.$set(this.model,"requireQuantity",requireQuantity)
			} else {
				this.$set(this.model,"requireQuantity",0)
			}
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.orgCodeTxt + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.applicationId = this.userInfo.empId //当前登录人
      this.model.applicationDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.model = await Object.assign({}, data)
			this.$set(this.model,'staffingQuantity',String(data.staffingQuantity?data.staffingQuantity : ''))
			this.$set(this.model,'practicalQuantity',String(data.practicalQuantity?data.practicalQuantity : ''))
			this.$set(this.model,'requireQuantity',String(data.requireQuantity?data.requireQuantity : ''))
			this.formData = this.model.itemList
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
				if (!this.formData.length) {
				  this.$u.toast('请添加岗位明细信息！')
				  return Promise.reject('请添加岗位明细信息！')
				}
			})
    },
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		},
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url({
					...this.model,
					itemList: this.formData
				})
			  this.$u.toast(response.message)
			  if (response.success) {
			    var that = this
			    
			    // 获取流程列表
			    if (this.model.id) {
			    	this.getProcessList(this.model.id)
			    } else {
			    // 判断添加的时候是否有返回id值
			    	if (response.result) {
			    		this.getProcessList(response.result)
			    	}
			    
			    }
			    this.$refs.uToast.show({
			    	message: response.message,
			    	type: 'default',
			    	complete () {
			    		// that.isSubmit = false
			    	}
			    })
			  }
			} finally {
        // error
			}
    },
    async onDraft() {
      // await this.validateForm()
			this.isSubmit = true
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url({
					...this.model,
					itemList: this.formData
				})
			  if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
			  }
			} finally {
        // error
			}
    },
  }
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
</style>
